import { View, Text, Image } from '@tarojs/components'
import Taro, { useLoad } from '@tarojs/taro'
import { OsSearch } from 'ossaui'
import './search.scss'
import { useState } from 'react'

export default function Index() {
  const [list, setList] = useState([])
  const [his, sethis] = useState([])
  const [value, setValue] = useState('')

  useLoad(() => {
    console.log('Page loaded.')
  })

  const fetch = (value) => {
    const index = his.findIndex(item => item === value);
    if (index > -1) {
      his.splice(index, 1)
    }
    sethis([value, ...his])
    Taro.request({
      url: 'http://localhost:3000/list',
      data: {
        title_like: value
      }
    }).then(res => {
      setList(res.data)
    })
  }

  return (
    <View className='index'>
      <OsSearch
        controlled
        value={value}
        onBlur={(e) => {
          const { value } = e.detail;
          fetch(value)
        }}
        onChange={(e, val) => {
          setValue(val)
        }}
      ></OsSearch>
      <View>
        {
          his.map(item => {
            return <View onClick={() => {
              setValue(item)
              fetch(item)
            }}>{item}</View>
          })
        }
      </View>
      <View>
        {
          list.map(item => {
            return (
              <View
                className='item'
                onClick={() => {
                  Taro.navigateTo({
                    url: '/pages/detail/detail?id=' + item.id
                  })
                }}
              >
                <Image src={item.image} className='itemImage' />
                <View className='itemDetail'>
                  <Text className='itemTitle'>{item.title}</Text>
                  <Text className='itemPrice'>¥ {item.price}</Text>
                </View>
              </View>
            )
          })
        }
      </View>
    </View >
  )
}
